package com.example.xd.tuiliu_test.videoplayer.lifecyclemanager;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.util.HashSet;
import java.util.Set;

public class LifecycleManagerFragment extends Fragment {
    private Set<ILifecycle> iLifecycles;
    String TAG = "fengao";

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (iLifecycles == null) {
            return;
        }
        for (ILifecycle lifecycle : iLifecycles) {
            if (lifecycle != null) {
                lifecycle.onCreate();
            }
        }
    }

    public void registerILifecycle(ILifecycle lifecycle) {
        if (iLifecycles == null) {
            iLifecycles = new HashSet<>();
        }
        iLifecycles.add(lifecycle);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.i(TAG, "onDetach: ");

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i(TAG, "onStart: ");
        if (iLifecycles == null) {
            return;
        }
        for (ILifecycle lifecycle : iLifecycles) {
            if (lifecycle != null) {
                lifecycle.onStart();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i(TAG, "onStop: ");
        if (iLifecycles == null) {
            return;
        }
        for (ILifecycle lifecycle : iLifecycles) {
            if (lifecycle != null) {
                lifecycle.onStop();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.i(TAG, "onDestroyView: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (iLifecycles == null) {
            return;
        }
        for (ILifecycle lifecycle : iLifecycles) {
            if (lifecycle != null) {
                lifecycle.onDestroy();
            }
        }
        iLifecycles.clear();
        iLifecycles = null;
    }

    public void removeILifecycle(ILifecycle lifecycle) {
        if (iLifecycles != null) {
            iLifecycles.remove(lifecycle);
        }
    }
}
